const {
  othersApi,
  myApi
} = require('../../../api/index')

const app = getApp()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    IsShowAttention: false,
    tagActiveT: 0,
    IMGBASEURL: app.globalData.IMGBASEURL,
    dynamicStyle: 0, //头部安全距离
    dayStyle: 0, //用户头部定位后的安全距离
    isTitle: false, //滑动后头部的变化
    tabTop: 0, //tab的粘性定位距离
    draw: false,
    drawActive: false,
    active: 1,
    tabList: ['灵感', '模型'],
    showWarnConfirm: false,
    welfareMessge: {},
    user: {}, //用户信息
    attentionFansCollect: {}, //或获赞数
    pageIndex: 1,
    pageCount: 10,
    listData: [],
    leftList: [],
    rightList: [],
    lodding: false,
    id: "",
    checkboxActive: "../../../assets/login/checkbox_def.svg",
    signActive: 1,
    signList: {},
    imgVip: [
      "../../../assets/my/yhdj_A1@2x.png",
      "../../../assets/my/yhdj_A2@2x.png",
      "../../../assets/my/yhdj_A3@2x.png",
      "../../../assets/my/yhdj_A4@2x.png",
      "../../../assets/my/yhdj_A5@2x.png",
      "../../../assets/my/yhdj_A6@2x.png",
      "../../../assets/my/yhdj_A7@2x.png",
      "../../../assets/my/yhdj_A1@2x.png"
    ],
    identityImg: [
      '',
      'icon_vip_normal-16@3x.png',
      'icon_vip_month-16@3x.png',
      'icon_vip_quarter-16@3x.png',
      'icon_vip_year-24@3x.png',
      'icon_vip_tryout-16@3x.png',
      'icon_vip_week-16@3x.png'
    ],
    vipBackgroundImg: '',
    joiAssociationData: true,
    presentInspiration: 0,
    routerUserId: "",
    dialogKey: '',
    attentionType: null,
    promptCopy: "",
    routerUserCode: ""
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const token = wx.getStorageSync('token')
    let {
      code
    } = options
    this.setData({
      routerUserCode: code,
    })
    //  获取安全距离
    wx.getSystemInfo({
      success: res => {
        let systemInfo = wx.getSystemInfoSync()
        let info = wx.getMenuButtonBoundingClientRect()
        this.setData({
          height: (info.top - systemInfo.statusBarHeight) * 2 + info.height,
          dynamicStyle: (res.statusBarHeight) + "px",
          dayStyle: (info.top - systemInfo.statusBarHeight) * 2 + info.height + res.statusBarHeight + "px",
          tabTop: (info.top - systemInfo.statusBarHeight) * 2 + info.height + res.statusBarHeight + "px"
        })
      },
      fail(err) {
        console.log(err);
      }
    })
    this.getOthersPeoplesInformationr()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    let thet = this
    if (this.data.active === 1) {
      this.setData({
        tab1: "tab-item tab-left tab-active",
        tab2: "tab-item",
        listData: [],
        leftList: [],
        rightList: [],
        pageIndex: 1,
        active: 1
      })

      this.onHide()
    }



  },
  /**
   * 返回上一级
   */
  toPage() {
    wx.navigateBack()
  },
  /**
   * 关闭登录弹窗
   */
  onHide() {
    const popup = this.selectComponent('#popupid');
    if (popup.data.visible) {
      popup.setData({
        visible: false
      })
      this.isAttention()
    }

  },

  /**
   * 获取他人信息
   */
  getOthersPeoplesInformationr() {
    othersApi.getothers({
      UserCode: this.data.routerUserCode,
    }).then((res => {
      let Result = res.Result
      let id = res.Result.UserId
      this.setData({
        user: Result,
        routerUserId: id
      })
      this.init(1)
      this.isAttention()
      this.membershipLevel(this.data.user)
      this.getFlow()
    }))
  },
  /*
   *获取获赞和粉丝和关注
   */
  getFlow() {
    othersApi.getAchievements({
      ID: this.data.routerUserId
    }).then((res) => {
      this.setData({
        attentionFansCollect: res.Result
      })
    })
  },

  /*
   *  获取我的创作
   */
  // getCreative() {
  //   if (!this.data.id) {
  //     this.setData({
  //       pageIndex: 1
  //     })
  //     this.init(1)
  //   }
  //   let UserId = this.data.user.UserId
  //   this.setData({
  //     id: UserId
  //   })
  // },

  /**
   * 判断当前是否需已关注
   */
  isAttention() {
    const token = wx.getStorageSync("token");
    if (token) {
      othersApi.isAttention({
        ID: this.data.routerUserId,
      }).then((res => {
        this.setData({
          IsShowAttention: res.Result
        })
      }))
    }
  },

  /**
   * 操作关注或者取消关注
   */
  operationalConcern(e) {
    const token = wx.getStorageSync("token");
    if (token) {
      let type = e.currentTarget.dataset.type
      let text = type != 1 ? '是否取消关注' : '是否确定关注'
      this.setData({
        showWarnConfirm: true,
        attentionType: type,
        promptCopy: text
      })
    } else {
      this.shudLogin();
    }


  },
  /**
   * 取消关注
   */
  closeDialog() {
    this.setData({
      showWarnConfirm: false
    })
  },
  /**
   * 确定关注
   */
  confirm() {
    switch (this.data.attentionType) {
      case 1:
        othersApi.attentionUser({
          ID: this.data.routerUserId,
        }).then((res => {
          if (res.StatusCode == 200) {
            this.setData({
              IsShowAttention: true,
              showWarnConfirm: false
            })
            // wx.showToast({
            //   title: '复制成功',
            //   icon: 'none'
            // });
          } else {
            wx.showToast({
              title: `${res.Message}`,
              icon: "none"
            })
          }
        }))
        break;
      case 2:
        othersApi.unfollow({
          ID: this.data.routerUserId,
        }).then((res => {
          if (res.StatusCode == 200) {
            this.setData({
              IsShowAttention: false,
              showWarnConfirm: false
            })
          } else {
            wx.showToast({
              title: `${res.Message}`,
              icon: "error"
            })
          }
        }))
        break;
    }
  },

  // 复制草图里号
  copyCode() {
    wx.setClipboardData({
      data: `${this.data.user.UserCode}`,
      success(res) {
        wx.showToast({
          title: '复制成功',
          icon: 'none'
        });
      }
    });
  },
  onDelet(e) {
    let arr = this.data.listData.filter(el => el.id != e.detail.id)
    this.setData({
      listData: arr
    })
  },

  // loadMyModelList(e) {
  //   const index = e.currentTarget.dataset['index']
  //   this.setData({
  //     tagActiveT: index,
  //     listData: [],
  //     pageIndex: 1
  //   })
  //   this.init(3)
  // },

  // vip图片筛选
  vipGradeFun(value) {
    switch (value) {
      case "VIP001":
        return 0;
      case "VIP002":
        return 1;
      case "VIP003":
        return 2;
      case "VIP004":
        return 3;
      case "VIP005":
        return 4;
      case "VIP006":
        return 5;
      case "VIP007":
        return 6;
    }
  },
  // 会员等级背景筛选
  membershipLevel(grade) {
    let arr = ['', 'vip_normal bg@2x.png', 'vip_trial-bg@2x.png', 'vip_week-bg@2x.png', 'vip_month-bg@2x.png', 'vip_quarter-bg@2x.png', 'vip-year-bg@2x.png']
    this.setData({
      vipBackgroundImg: arr[grade.VIPWeight]
    })
  },

  onPullDownRefresh() {
    if (this.data.active == 1) {
      this.setData({
        tab1: "tab-item tab-left tab-active",
        tab2: "tab-item",
        listData: [],
        leftList: [],
        rightList: [],
        pageIndex: 1,
        active: 1
      })
      this.init(1)
    } else if (this.data.active == 2) {
      this.setData({
        tab1: "tab-item tab-left ",
        tab2: "tab-item tab-active",
        listData: [],
        leftList: [],
        rightList: [],
        pageIndex: 1,
        active: 2
      })
      this.init(2)
    }
  },
  // 礼物的显示隐藏
  inspiration() {
    this.setData({
      draw: "block"
    })
  },
  inspirationClose() {
    this.setData({
      draw: "none"
    })
  },
  // tab栏
  tabActive(e) {
    let index = e.currentTarget.dataset['value']
    this.setData({
      listData: [],
      leftList: [],
      rightList: [],
      pageIndex: 1,
      active: index
    })
    this.init(index)
  },

  /**
   * 查看列表详情
   */
  particularsItem(e) {
    wx.previewImage({
      current: e.currentTarget.dataset.url.coverImage, // 当前显示图片的http链接
      urls: e.currentTarget.dataset.url.images // 需要预览的图片http链接列表
    })
    return
  },

  /**
   * 福利任务
   */
  welfareTask(e) {
    console.log();
    wx.navigateTo({
      url: './welfareTask/welfareTask?id=' + e.currentTarget.dataset['id'],
    })
  },

  // 登录
  immediatelyLoge() {
    wx.navigateTo({
      url: '../login/index',
    })
  },
  splitArray(arr) {
    const mid = Math.ceil(arr.length / 2);
    const firstHalf = arr.slice(0, mid);
    const secondHalf = arr.slice(mid);
    return [firstHalf, secondHalf];
  },
  // 1 我的创作 2 我的收藏
  async init(value) {
    let cIndex = this.data.tagActiveT
    let thet = this
    thet.setData({
      lodding: false
    })
    if (value == 1) {
      othersApi.getInspiration({
        ID: this.data.routerUserId,
        PageIndex: thet.data.pageIndex,
        PageSize: 10,
      }).then((res => {
        thet.setData({
          listData: [...thet.data.listData, ...res.Result.Datas],
          pageIndex: thet.data.pageIndex + 1
        })
        const rres = this.splitArray(res.Result.Datas)
        if (this.data.listData.length > 0) {
          this.setData({
            leftList: [...this.data.leftList, ...rres[0]],
            rightList: [...this.data.rightList, ...rres[1]],
          })
        }
        if (thet.data.listData.length >= res.Result.TotalCount) {
          thet.setData({
            lodding: true
          })
        }
      }))
    } else {
      othersApi.getModelList({
        creatorId: this.data.routerUserId,
        PageIndex: thet.data.pageIndex,
        PageSize: 10,
      }).then((res => {
        thet.setData({
          listData: [...thet.data.listData, ...res.items],
          pageIndex: thet.data.pageIndex + 1
        })
        const rres = this.splitArray(res.items)
        if (this.data.listData.length > 0) {
          this.setData({
            leftList: [...this.data.leftList, ...rres[0]],
            rightList: [...this.data.rightList, ...rres[1]],
          })
        }
        if (thet.data.listData.length >= res.totalPages) {
          thet.setData({
            lodding: true
          })
        }
      }))
    }
    wx.stopPullDownRefresh();
  },
  onerror(e) {
    let user = this.data.user
    user.Avatar = this.data.IMGBASEURL + "user_64.png"
    this.setData({
      user: user
    })
  },
  readRend(id) {
    const arr = this.data.listData.filter((e) => e.ID != id)
    const rres = this.splitArray(arr)
    this.setData({
      leftList: rres[0],
      rightList: rres[1],
    })
  },

  /**
   * 点击不在提醒
   */
  remind() {
    if (this.data.checkboxActive == "../../../assets/login/checkbox_def.svg") {
      this.setData({
        checkboxActive: "../../../assets/login/checkbox_sel.svg"
      })
    } else {
      this.setData({
        checkboxActive: "../../../assets/login/checkbox_def.svg"
      })
    }
  },


  /**
   * 加入社群
   */
  joiAssociation() {
    wx.navigateTo({
      url: './association/association',
    })
  },

  /**
   * 删除加入社群
   */
  joiAssociationDelete() {
    this.setData({
      joiAssociationData: false
    })
  },
  succeedClose() {
    this.setData({
      drawActive: false
    })
  },

  onPageScroll: function (event) {
    const app = getApp()
    let tab = wx.createSelectorQuery()
    tab.select('#tab').boundingClientRect((res) => {
      if (res.top > app.globalData.navHeight + 44) {
        this.setData({
          isTitle: false
        })
      } else {
        this.setData({
          isTitle: true
        })
      }
    }).exec()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    if (this.data.lodding) {
      return
    } else {
      this.init(this.data.active)
    }
  },

  toDetail(e) {
    let {
      item
    } = e.currentTarget.dataset
    wx.navigateTo({
      url: `/pages/modelStore/modelDetail/index?id=${item.id}`,
    })
  },
  //去登录
  shudLogin() {
    const popup = this.selectComponent("#popupid");
    console.log("popup", popup);
    popup.setData({
      visible: true,
      isNavBar: false,
    });
  },

})